package enterprise.manage.web.interceptor;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ThemeResolver;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.support.RequestContextUtils;

import java.util.List;

/**
 * Interceptor that allows for changing the current theme on every request,
 * via a configurable request parameter.
 *
 * @author Juergen Hoeller
 * @see org.springframework.web.servlet.ThemeResolver
 * @since 20.06.2003
 */
public class ThemeChangeInterceptor extends HandlerInterceptorAdapter {

    /**
     * Default name of the theme specification parameter: "theme".
     */
    public static final String DEFAULT_PARAM_NAME = "theme";
    /**
     * 参数名字
     */
    private String paramName = DEFAULT_PARAM_NAME;

    /**
     * 为了避免非法指定不存在的皮肤，可以设定存在皮肤的集合，以备检查
     */
    private List<String> themeNames;

    /**
     * 设定一个主题存在于request的名字，供页面调用
     */
    private String decoratorThemeName = "theme";


    /**
     * Set the name of the parameter that contains a theme specification
     * in a theme change request. Default is "theme".
     *
     * @param paramName paramName
     */
    public void setParamName(String paramName) {
        this.paramName = paramName;
    }

    public void setThemeNames(List<String> themeNames) {
        this.themeNames = themeNames;
    }

    public void setDecoratorThemeName(String decoratorThemeName) {
        this.decoratorThemeName = decoratorThemeName;
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws ServletException {

        ThemeResolver themeResolver = RequestContextUtils.getThemeResolver(request);
        if (themeResolver == null) {
            throw new IllegalStateException("No ThemeResolver found: not in a DispatcherServlet request?");
        }
        String newTheme = request.getParameter(this.paramName);
        if (newTheme != null && (themeNames == null || themeNames.isEmpty() || themeNames.contains(newTheme))) {
            themeResolver.setThemeName(request, response, newTheme);
        }

        //主题存入request，供页面调用
        request.setAttribute(decoratorThemeName, RequestContextUtils.getTheme(request).getName());
        // Proceed in any case.
        return true;
    }

}
